using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

namespace CSharpXDL
{
    class BlockDownloader : XRun
    {
        public void run() {
		int count = 0;
		aging: while (count < 100) {
			
			try {
				if (count > 0)
                    Console.WriteLine(fName + " reStart. ");
				long unReadLen= total- readed;
//				System.out.println(fName+" "+total+" "+unReadLen+" "+ file.length());
				if (unReadLen <= 0) {
					completed = true;
					downloader.complete(fName);
					return;
				}
			   HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url1);

                httpRequest.AddRange()
               if (httpRequest.HaveResponse)
               {

               }
			
				String property = "bytes=" + (partial + readed) + "-";
				connection.setRequestProperty("RANGE", property);
				connection.setRequestProperty("User-Agent","Xbox Live Client/2.0.14719.0");
				connection.setRequestProperty("Host",u.getHost());
				int responseCode = ((HttpURLConnection)connection).getResponseCode();
				if(responseCode>499)throw new RuntimeException("net connect Error ResponseCode "+responseCode);


                BinaryReader binReader =   new BinaryReader(File.Open(fileName, FileMode.Open));



				inputStream = connection.getInputStream();
				ReadableByteChannel newChannel = Channels
						.newChannel(inputStream);
				 Console.WriteLine(fName + " start time:"
						+ new Date().toLocaleString());
				long position = partial+readed;
				
				long len = 0;
				int allocate=unReadLen>=blockL?blockL:(int)unReadLen;
				ByteBuffer buffer=ByteBuffer.allocate(allocate);
				
				while ( unReadLen>0) {
					len = newChannel.read(buffer);
					if (len == 0 && unReadLen > 0) {
						try {
							newChannel.close();
							stream.close();
							inputStream.close();
						} catch (Exception e) {
						}
						count++;
						goto aging;
					}
					position = partial+readed;
					unReadLen -= len;
					buffer.rewind();
					int writed=0;
					while((writed+=channel.write(buffer, position+writed))<len){
						 Console.WriteLine(fName+":"+writed);
					}
					buffer.rewind();
					readed+=len;
					buffer=unReadLen>=blockL?buffer:ByteBuffer.allocate((int)unReadLen);
				}
				
				completed = true;
				downloader.complete(fName);
				inputStream.close();
				return;
			} catch (Exception e) {
				e.printStackTrace();
				try {
					if (stream != null) {
						stream.flush();
						stream.close();
					}
					if (inputStream != null)
						inputStream.close();

					sleep(5000);
				} catch (Exception e1) {

					e1.printStackTrace();
				}
				 Console.WriteLine(fName +" "+e.getMessage()+ " Exception time:"
						+ new Date().toLocaleString());
				count++;
				continue ;
			}
		}

	}

        public long length()
        {
            return readed;
        }
    }
}
